/*
 * @Description: 
 * @Author: wangyigang
 * @Date: 2022-09-05 15:59:31
 * @LastEditTime: 2022-09-06 08:21:15
 * @LastEditors: wangyigang
 */
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
 function activate(context) {
    console.log('Congratulations, your extension "wyg-vscode-log" is now active!');
    // 获取当前编辑器对象
    let currentEditor = vscode.window.activeTextEditor;
    // 当编辑器文本变化时，重置编辑器对象
    vscode.window.onDidChangeActiveTextEditor(editor => (currentEditor = editor));
		// 注册命令
    const disposable = vscode.commands.registerTextEditorCommand('console.with.prefix', () => {
        new Promise((resolve, reject) => {
            let sel = currentEditor.selection; // 获取选中区域
            const reg = /[\S]+\.(log)$/; // 规定匹配log的正则
            // 通过getWordRangeAtPosition方法得到单词范围对象
            let ran = currentEditor.document.getWordRangeAtPosition(sel.anchor, reg);
            if (ran == undefined) {
                reject('please use this statements：xxx.log');
            } else {
                let doc = currentEditor.document; // 获取当前文档对象
                let line = ran.start.line; // 获取行数
                let item = doc.getText(ran); // 通过getText方法获取文本
                let prefix = item.replace('.log', '');
                // 获取当前行的第一个非空字符的偏移量
                let idx = doc.lineAt(line).firstNonWhitespaceCharacterIndex; 
                let wrapData = {
                    idx,
                    ran,
                    line,
                    txt: `console.log('${prefix}========',${prefix});`
                };
                resolve(wrapData);
            }
        }).then(wrap => {
                currentEditor
                .edit(e => {
                    // 将旧文本替换成新文本 主要的功能就是靠这行代码实现
                    e.replace(wrap.ran, wrap.txt);
                }).then(() => {
                    // 把光标定位到末尾
                    currentEditor.selection = new vscode.Selection(
                        new vscode.Position(wrap.line, wrap.txt.length + wrap.idx),
                        new vscode.Position(wrap.line, wrap.txt.length + wrap.idx)
                    );
               });
          }).catch(message => {
          		console.log('REJECTED_PROMISE:' + message);
          });
    });
    context.subscriptions.push(disposable);
}


// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
